// 搜索病友圈
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { LeftOutline } from 'antd-mobile-icons'
import request from '../../api/request'
import { getStorage, setStorage, removeStorage } from '../../utils/storage'
import './Search.css'

interface SearchResult {
  sickCircleId: number;
  title: string;
  detail: string;
  releaseTime: number;
  collectionNum: number;
  commentNum: number;
  amount: number;
}

interface SearchResponse {
  status: string;
  message: string;
  result: SearchResult[];
}

const PatientCircleSearch = () => {
  const navigate = useNavigate();
  const [searchKeyword, setSearchKeyword] = useState('');
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [hasSearched, setHasSearched] = useState(false);
  const [showSuggestions, setShowSuggestions] = useState(false);

  // 从本地存储加载搜索历史
  useEffect(() => {
    const history = getStorage<string[]>('searchHistory', []);
    setSearchHistory(history);
  }, []);

  // 保存搜索历史到本地存储
  const saveSearchHistory = (keyword: string) => {
    if (!keyword.trim()) return;
    
    const newHistory = [keyword, ...searchHistory.filter(item => item !== keyword)].slice(0, 10);
    setSearchHistory(newHistory);
    setStorage('searchHistory', newHistory);
  };

  // 清除搜索历史
  const clearSearchHistory = () => {
    setSearchHistory([]);
    removeStorage('searchHistory');
  };

  // 执行搜索
  const performSearch = async (keyword: string) => {
    if (!keyword.trim()) return;
    
    setIsSearching(true);
    setHasSearched(true);
    setShowSuggestions(false);
    
    try {
      const response = await request.get('/health/user/sickCircle/v1/searchSickCircle', {
        params: { keyWord: keyword }
      }) as SearchResponse;
      
      if (response.status === '0000' && response.result) {
        setSearchResults(response.result);
      } else {
        setSearchResults([]);
      }
    } catch (error) {
      console.error('搜索失败:', error);
      setSearchResults([]);
    } finally {
      setIsSearching(false);
    }
  };

  // 处理搜索按钮点击
  const handleSearch = () => {
    if (searchKeyword.trim()) {
      saveSearchHistory(searchKeyword.trim());
      performSearch(searchKeyword.trim());
    }
  };

  // 处理搜索历史项点击
  const handleHistoryItemClick = (keyword: string) => {
    setSearchKeyword(keyword);
    performSearch(keyword);
  };

  // 处理回车键搜索
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  // 处理输入框变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchKeyword(value);
    
    const trimmed = value.trim();
    if (trimmed) {
      setShowSuggestions(true);
    } else {
      // 清空时恢复初始状态
      setShowSuggestions(false);
      setHasSearched(false);
      setIsSearching(false);
      setSearchResults([]);
    }
  };

  // 处理建议项点击
  const handleSuggestionClick = (suggestion: string) => {
    setSearchKeyword(suggestion);
    setShowSuggestions(false);
    performSearch(suggestion);
  };

  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };

  // 跳转到详情页
  const handlePostClick = (postId: number) => {
    navigate(`/patient-circle/detail/${postId}`);
  };

  // 格式化时间戳
  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  };

  // 生成搜索建议（基于历史记录）
  const generateSuggestions = () => {
    if (!searchKeyword.trim()) return [];
    
    return searchHistory
      .filter(item => item.toLowerCase().includes(searchKeyword.toLowerCase()))
      .slice(0, 5);
  };

  return (
    <div className="search-page">
      {/* 搜索头部 */}
      <div className="search-header">
        <div className="search-back" onClick={handleBack}>
          <LeftOutline />
        </div>
        <div className="search-input-container">
          <input
            type="text"
            className="search-input"
            placeholder="请输入病症名称或标题关键字"
            value={searchKeyword}
            onChange={handleInputChange}
            onKeyPress={handleKeyPress}
            onFocus={() => searchKeyword.trim() && setShowSuggestions(true)}
          />
          {/* 搜索建议 */}
          {showSuggestions && (
            <div className="search-suggestions">
              {generateSuggestions().map((suggestion, index) => (
                <div
                  key={index}
                  className="suggestion-item"
                  onClick={() => handleSuggestionClick(suggestion)}
                >
                  {suggestion}
                </div>
              ))}
            </div>
          )}
        </div>
        <button className="search-button" onClick={handleSearch}>
          搜索
        </button>
      </div>

      {/* 搜索内容区域 */}
      <div className="search-content">
        {!hasSearched ? (
          // 搜索历史
          <div className="search-history">
            <div className="history-header">
              <span className="history-title">搜索历史</span>
              {searchHistory.length > 0 && (
                <button className="clear-history" onClick={clearSearchHistory}>
                  清除
                </button>
              )}
            </div>
            <div className="history-list">
              {searchHistory.map((keyword, index) => (
                <div
                  key={index}
                  className="history-item"
                  onClick={() => handleHistoryItemClick(keyword)}
                >
                  {keyword}
                </div>
              ))}
            </div>
          </div>
        ) : (
          // 搜索结果
          <div className="search-results">
            {isSearching ? (
              <div className="loading">搜索中...</div>
            ) : searchResults.length > 0 ? (
              <div className="results-list">
                {searchResults.map((result) => (
                  <div
                    key={result.sickCircleId}
                    className="result-item"
                    onClick={() => handlePostClick(result.sickCircleId)}
                  >
                    <div className="result-header">
                      <h3 className="result-title">{result.title}</h3>
                    </div>
                    <div className="result-time">
                      {formatTime(result.releaseTime)}
                    </div>
                    <div className="result-detail">
                      {result.detail}
                    </div>
                    <div className="result-actions">
                      <span className="result-collection">收藏 {result.collectionNum}</span>
                      <span className="result-comment">建议 {result.commentNum}</span>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="no-results">
                未找到相关结果
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default PatientCircleSearch;